<?php
/**
 * Created by PhpStorm.
 * User: liuxiaojie
 * Date: 2019-03-10
 * Time: 22:51
 */

namespace app\ops\controller;

class Mycoupon extends Base

{

    function index()
    {
        $list = db('my_coupon m')
            ->join('coupon c', 'c.coupon_id = m.coupon_id')
            ->join('customer u', 'u.id = m.customer_id')
            ->where([])
            ->field('m.id, c.name, u.nickname, m.status, m.start_time, m.end_time')
            ->order('m.id desc')
            ->paginate(10)->each(function (&$item){
                if($item['status'] == 1)
                {
                    if(strtotime($item['end_time']) < time())
                    {
                        $item['status'] = 3;
                    }
                }
                return $item;
            });

        $this->assign('list', $list);
        return $this->fetch();
    }

    function edit($id = 0)
    {
        $post = request()->post();
        if($post)
        {
            $data = db('coupon')->where(['coupon_id'=> $post['coupon_id']])->field('expired_type, start_time, expired_date, uid')->find();
            if($data['expired_type'] == 1)
            {
                $post['start_time'] = $data['start_time'];
            }else{
                $post['start_time'] = date('Y-m-d');
            }
            $post['end_time'] = date('Y-m-d', strtotime($post['start_time']) + $data['expired_date'] * 86400);
            $post['uid'] = $data['uid'];
            if($post['id'])
            {
                db('my_coupon')->update($post);
            }else{
                unset($post['id']);
                db('my_coupon')->insert($post);
            }
            return success([]);
        }else{
            $data = db('my_coupon')->where(['id'=> $id])->find();
            $this->assign('data', $data);
            return $this->fetch();
        }
    }
}